package service

import (
	"errors"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/admin/service/dto"
	"tuowei.com/common/actions"
	cDto "tuowei.com/common/dto"
	"tuowei.com/pkg/xlog"
)

type SysCourseGift struct {
	service.Service
}

// GetPage 获取SysCourseGift列表
func (e *SysCourseGift) GetPage(c *dto.SysCourseGiftGetPageReq, p *actions.DataPermission, list *[]models.SysCourseGift, count *int64) error {
	var err error
	var data models.SysCourseGift

	err = e.Orm.Debug().Preload("Dept").
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		xlog.Errorf("db error: %s", err)
		return err
	}
	return nil
}

// Insert 创建SysCourseGift对象
func (e *SysCourseGift) Insert(c *dto.SysCourseGiftInsertReq) (int, error) {
	var err error
	var data models.SysCourseGift
	var i int64
	err = e.Orm.Model(&data).Where("gift_type = ?", c.GiftType).Where("course_id = ?", c.CourseId).Count(&i).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return 0, err
	}
	if i > 0 {
		err := errors.New("已存在赠送题库和模拟试卷！")
		e.Log.Errorf("db error: %s", err)
		return 0, err
	}
	c.Generate(&data)

	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return 0, err
	}
	return data.Id, nil
}

func (e *SysCourseGift) Update(c *dto.SysCourseGiftUpdateReq) error {
	var err error
	var model = models.SysCourseGift{}
	c.Generate(&model)
	db := e.Orm.Where("course_id = ?", c.CourseId).Update("obj_id", c.ObjIds)
	err = db.Error
	if err != nil {
		e.Log.Errorf("Service UpdateStatus error:%s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")

	}
	return nil
}

// Remove 删除SysCourseGift
func (e *SysCourseGift) Remove(c *dto.SysCourseGiftById, p *actions.DataPermission) error {
	var err error
	var data models.SysCourseGift

	db := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).Delete(&data, c.GetId())
	if err = db.Error; err != nil {
		e.Log.Errorf("Error found in  RemoveSysUser : %s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

// Get 获取SysConfig对象
func (e *SysCourseGift) Get(courseId int, courseType string) (data []*models.SysCourseGift, err error) {
	err = e.Orm.Where("course_id = ?", courseId).Where("course_type = ?", courseType).Find(&data).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service SysCourseGiftGetReq error:%s", err)
		return nil, err
	}
	if err != nil {
		e.Log.Errorf("Service SysCourseGiftGetReq error:%s", err)
		return nil, err
	}
	return data, nil
}
